/**
 * Copyright (2024, ) Institute of Software, Chinese Academy of Sciences
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.ac.iscas;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import cn.ac.iscas.protocols.HttpProtocol;
import cn.ac.iscas.sources.JSONSource;
import cn.ac.iscas.sources.http.HttpAPiKeySource;
import cn.ac.iscas.sources.http.HttpPublicSource;
import cn.ac.iscas.sources.http.json.MisumiSource;
import cn.ac.iscas.utils.HtmlUtil;
import cn.ac.iscas.utils.HttpUtil;
import cn.ac.iscas.utils.JsonUtil;

/**
 * 
 * It is used for creating various HttpRequest
 * 
 * @author wuheng@iscas.ac.cn
 * @since 1.0.0
 **/
public class Main {

	public static void main(String[] args) throws Exception {

		zkh();
	}

	private static void insert() throws SQLException, IOException {
		String jdbcUrl = "jdbc:postgresql://192.168.42.138:30306/2023yfb3308702"; // 替换为你的数据库URL
		String username = "postgres"; // 替换为你的数据库用户名
		String password = "onceas"; // 替换为你的数据库密码

		Connection conn = DriverManager.getConnection(jdbcUrl, username, password);

		// SQL插入语句
		String sql = "INSERT INTO goods (name, subclass, catalog, source) VALUES (?, ?, ?, ?)";

		ArrayNode misumi = (ArrayNode) new ObjectMapper().readTree(new File("results/zkh-result.data"));

		for (JsonNode item : misumi) {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			// 设置参数值
			pstmt.setString(1, item.get("name").asText());
			pstmt.setString(2, item.get("subclass").asText());
			pstmt.setString(3, item.get("catalog").asText());
			pstmt.setString(4, "震坤行");

			// 执行插入操作
			int rowsAffected = pstmt.executeUpdate();
			if (rowsAffected > 0) {
				System.out.println("数据插入成功！");
			} else {
				System.out.println("数据插入失败。");
			}
		}
	}

//		zkh();

//		misumi();

	private static void zkh() throws Exception {
		ArrayNode list = new ObjectMapper().createArrayNode();

		JSONSource json = new MisumiSource("sources/zkh-metadata.data");
		Iterator<Map.Entry<String, JsonNode>> virtual = JsonUtil.iterator(json.getJson());
		Map<String, Object> vMap = JsonUtil.values(virtual);
		for (String name : vMap.keySet()) {
			Iterator<Map.Entry<String, JsonNode>> catalog = JsonUtil.iterator((JsonNode) vMap.get(name));
			Map<String, Object> cMap = JsonUtil.values(catalog);
			for (String key : cMap.keySet()) {
//				HttpPublicSource http = new HttpPublicSource(HttpUtil.from(
//						"https://www.zkh.com/servezkhApi/catalog/getTwoAndThreeLevelCatalogByCatalogId/" + key,
//						HttpUtil.GET));
//				HttpGet get = HttpProtocol.get(http);
//				JsonNode resultJson = JsonUtil.getStream(get).get("result");
//				ArrayNode catalogJson = (ArrayNode) resultJson.get("children");
//
//				for (JsonNode subclassJson : catalogJson) {
//
//					for (JsonNode itemJson : (ArrayNode) subclassJson.get("children")) {
//						ObjectNode obj = new ObjectMapper().createObjectNode();
//						obj.put("name", itemJson.get("catalogName").asText());
//						obj.put("image", itemJson.get("imagePath").asText());
//						obj.put("subclass", subclassJson.get("catalogName").asText());
//						obj.put("catalog", resultJson.get("catalogName").asText());
//						list.add(obj);
//					}
//				}
				
				for (JsonNode itemJson : HtmlUtil.getZkhProds("https://www.zkh.com/list/c-" + key + ".html")) {
					ObjectNode obj = new ObjectMapper().createObjectNode();
					obj.put("image", itemJson.get("proImgPath_Z1").get(0).asText());
					obj.put("price", itemJson.get("sellingPrice").asDouble());
					obj.put("name", itemJson.get("proSkuProductName").asText());
					obj.set("spec", itemJson.get("specificationList"));
					obj.put("level3catalog", itemJson.get("level4CatalogueName").asText());
					obj.put("level2catalog", cMap.get(key).toString());
					obj.put("level1catalog", name);
					list.add(obj);
				}
			}
		}
		System.out.println(list.toPrettyString());
	}

	private static void misumi() throws Exception {
		ArrayNode list = new ObjectMapper().createArrayNode();

		JSONSource json = new MisumiSource("sources/misumi-metadata.data");

		Iterator<Map.Entry<String, JsonNode>> catalog = JsonUtil.iterator(json.getJson());

		Map<String, Object> cMap = JsonUtil.values(catalog);
		for (String name : cMap.keySet()) {
			System.out.println(name);
			Iterator<Map.Entry<String, JsonNode>> subclass = JsonUtil.iterator((JsonNode) cMap.get(name));
			Map<String, Object> sMap = JsonUtil.values(subclass);
			for (String key : sMap.keySet()) {
				System.out.println("- " + key);
				System.out.println("- " + sMap.get(key));

				HttpAPiKeySource http = new HttpAPiKeySource(
						HttpUtil.from("https://apihosts.misumi.com.cn/Customer/getCategoryInfo", HttpUtil.POST),
						"z7egOF19hr9DUxsvyGhkO69qMuCa2O8Y796BuksP");
				HttpPost post = HttpProtocol.post(http, "{\"categoryCode\":\"" + key + "\"}");
				ArrayNode childCategoryList = (ArrayNode) JsonUtil.getStream(post).get("data").get("childCategoryList");
				for (JsonNode childNode : childCategoryList) {
					String rname = childNode.get("categoryName").asText();
					ObjectNode obj = new ObjectMapper().createObjectNode();
					obj.put("name", rname);
					obj.put("subclass", sMap.get(key).toString());
					obj.put("catalog", name);
					list.add(obj);
				}
			}
		}

		System.out.println(list.toPrettyString());
	}


	// 微制造管控
//		casicloud();

	// 小程序
//		sv3d();

	// 金蝶云
//		HttpCookieSource cookie = new HttpCookieSource(
//		HttpUtil.from("https://console.kingdee.com/ierp/kapi/app/kded_order/listAddress?ajaxSendTime=1733108148451", HttpUtil.GET), 
//		"gr_user_id=5f6da531-5a8e-44a1-a066-b2c71e9088fe; _clck=9ccz1w%7C2%7Cfra%7C0%7C1794; locale=zh-CN; 8c9d5fbf00a08fc5_gr_last_sent_cs1=2094384078253177856; kd_pro_kdshareflag=; 819a5889dcb2672b_gr_session_id=72f7302a-d369-439f-ac92-3c7f240e7641; acplatform_sid=76fc3287-d610-4993-9f31-052fbe55cc4a; acplatform_stk=265e642a68417323e2fe1ade9daf0442b826cd184c4f1f85704be6f9f45f07896a5ea39bf6027247; 8c9d5fbf00a08fc5_gr_session_id=83b327fe-e917-42ea-99ae-9052c6ee6812; 8c9d5fbf00a08fc5_gr_last_sent_sid_with_cs1=83b327fe-e917-42ea-99ae-9052c6ee6812; KERPSESSIONIDkd_pro=1536230697407890389_KuXfCv4ChlfuHknu215lO8gs75U278IAbZDQ3J3vkS4PSY8hxBY82bif9pMkljIYnDR3njY96O3g35f9wgVOMa8n3ayeFhItJmTE; 8c9d5fbf00a08fc5_gr_cs1=2094384078253177856");

//		HttpGet httpGet = HttpProtocol.get(cookie);
//		getStream(httpGet);

//	}

//	private static void sv3d() throws IOException, ParseException {
//		HttpCookieSource cookie = new HttpCookieSource(
//				HttpUtil.from("https://sview.sv3d.cn/service/models/modelList", HttpUtil.POST), 
//				"SERVERID=9d6acf257c4b96bef3eb60e7a1fd71f9|1732868887|1732868887;Path=/");
//		
//		// https://service.sview3d.com/model/downloadsvl/20733e05-f9bf-430d-8274-4df7663bf0d7
//		HttpPost httpPost = HttpProtocol.post(cookie, "{}");
//		getStream(httpPost);
//	}
//
//	private static void casicloud() throws IOException, ParseException {
//		HttpTokenSource token = new HttpTokenSource(
//				HttpUtil.from("https://wzz.casicloud.com:8023/cloudapi/pmc/base/molds/page?pageNum=1&pageSize=10&filter=%7B%22ifDisable_B_EQ%22:false%7D", HttpUtil.GET), 
//				"bab2965b-c4c4-4e20-9050-1d75f82ae714");
//		
//		HttpGet httpGet = HttpProtocol.get(token);
//		getStream(httpGet);
//	}
//
	private static void getStream(HttpUriRequestBase http) throws Exception {
		try (CloseableHttpResponse response = HttpClients.createDefault().execute(http)) {

			// 获取响应状态码
			int statusCode = response.getCode();
			System.out.println("Response Status Code: " + statusCode);

			// 获取响应实体
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				// 将响应实体转换为字符串并打印
				String responseBody = EntityUtils.toString(entity);
				System.out.println("Response Body: " + responseBody);
			}
		}
	}
}
